/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.asseco.mio.codex.controllers;

import com.asseco.mio.codex.FirstLoginModel;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import java.math.BigInteger;
import java.security.MessageDigest;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.model.User;
import org.appfuse.service.GenericManager;
import org.appfuse.service.UserManager;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.asseco.mio.codex.FirstLoginModel;
import com.asseco.persistence.service.HibernateUtil;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.appfuse.model.User;
import org.appfuse.service.GenericManager;
import org.appfuse.service.UserManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 *
 * @author gjoko.mitrovski
 */
@Controller
@RequestMapping("/firstlogin*")
public class FirstLoginController extends BaseFormController {

    private UserManager userManager = null;

    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
    private GenericManager<FirstLoginModel, String> firstLoginManager;

    @Autowired
    public void setFirstLoginManager(@Qualifier("firstLoginManager") GenericManager<FirstLoginModel, String> firstLoginManager) {
        this.firstLoginManager = firstLoginManager;
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        return new ModelAndView("firstlogin").addObject("username", new User());
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(User user, BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String x = request.getRemoteUser();
        User username = userManager.getUserByUsername(x);
        String pass = user.getPassword();
        FirstLoginCheck firstLogin = new FirstLoginCheck();

        Locale locale = request.getLocale();

        // proverka na passwordot
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(FirstLoginModel.class).add(Restrictions.eq("username", x));

        List result = criteria.list();
        session.getTransaction().commit();

        boolean isPassOk = true;

        if (!result.isEmpty()) {
            FirstLoginModel y = (FirstLoginModel) result.get(0);


            if (pass.equals(y.getFirstPassword())) {
                saveMessage(request, getText("first.istPassSoOriginalen", locale));
                isPassOk = false;
            }

            if (!pass.equals(user.getConfirmPassword())) {
                saveMessage(request, getText("first.razlicniPasswordi", locale));
                isPassOk = false;
            }

            if (pass.length() < 6) {
                saveMessage(request, getText("first.podolgOd6", locale));
                isPassOk = false;
            }

            Matcher matcher;
            String USERNAME_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,})";
            Pattern pattern = Pattern.compile(USERNAME_PATTERN);
            matcher = pattern.matcher(pass);
            if (matcher.matches() == false) {
                saveMessage(request, getText("first.loshiKarakteri", locale));
                isPassOk = false;
            }


            //zachuvaj go passwordot i izbrishi go od tabela
            if (isPassOk) {
                MessageDigest m = MessageDigest.getInstance("SHA1");
                m.reset();
                m.update(pass.getBytes());
                byte[] digest = m.digest();
                BigInteger bigInt = new BigInteger(1, digest);
                String hashtext = bigInt.toString(16);
                username.setPassword(hashtext);
                userManager.save(username);
                y.setPasswordStatus(false);
                firstLoginManager.save(y);
                request.getSession().removeAttribute("firstLogin");
                request.getSession().setAttribute("notFirstLogin", locale);
                return new ModelAndView("mainMenu");
            }
            else {

                return new ModelAndView("firstlogin").addObject("username", new User());
            }
        }

        // end of remove
        return new ModelAndView("mainMenu");
        
    }
}
